package com.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.base.BasePageReq;
import com.base.BasePageRes;
import com.entity.ArticalChannel;
import com.exception.ServiceException;
import com.repository.ArticalChannelRepository;
import com.repository.ArticalRepository;
import com.res.ArticalChannelRes;
import com.res.ArticalRes;
import com.service.HomeServie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class HomeServieImpl implements HomeServie {
    @Autowired
    private ArticalChannelRepository articalChannelService;
    @Autowired
    private ArticalRepository articalRepository;
    @Autowired
    private ArticalServiceImpl articalService;
    @Override
    public BasePageRes queryPage(BasePageReq pageReq) {
        if (StringUtils.isEmpty(pageReq.getPage())) {
            throw new ServiceException("请传入page");
        }
        if (StringUtils.isEmpty(pageReq.getSize())) {
            throw new ServiceException("请传入size");
        }
        IPage<ArticalRes> pages = new Page<>(pageReq.getPage(), pageReq.getSize());
        IPage<ArticalRes> articalIPage = articalRepository.homePage(pages,pageReq);
        BasePageRes pageRes = articalService.convertIpage(articalIPage,  new ArticalRes());
        List<ArticalRes> articalResList = pageRes.getList();
        List<Long> articalIds = new ArrayList<>();
        for (int i = 0; i < articalResList.size(); i++) {
            articalIds.add(articalResList.get(i).getId());
        }
        if(CollectionUtils.isEmpty(articalIds)){
            return pageRes;
        }
        List<ArticalChannelRes> articalChannelRes = articalChannelService.queryChannel(articalIds);
        for (ArticalRes articalRes : articalResList) {
            List<ArticalChannelRes> channelRes = articalChannelRes.stream().filter(item -> {
                return Objects.equals(item.getArticalId(), articalRes.getId());
            }).collect(Collectors.toList());
            articalRes.setChannelList(channelRes);
        }
        return pageRes;
    }
}
